import { MigrationInterface, QueryRunner } from 'typeorm';

export class FixInvalidBirthdays1625000000002 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 获取所有用户
    const users = await queryRunner.query('SELECT id, birthday FROM users');
    
    // 修复无效的生日
    for (const user of users) {
      if (user.birthday) {
        try {
          // 尝试将生日转换为有效的日期对象
          const birthday = new Date(user.birthday);
          if (isNaN(birthday.getTime())) {
            console.log(`用户ID ${user.id} 的生日格式无效，设置为 NULL`);
            await queryRunner.query(
              `UPDATE users SET birthday = NULL WHERE id = ?`,
              [user.id]
            );
          }
        } catch (error) {
          console.log(`用户ID ${user.id} 的生日解析失败，设置为 NULL:`, error);
          await queryRunner.query(
            `UPDATE users SET birthday = NULL WHERE id = ?`,
            [user.id]
          );
        }
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 这个迁移不需要回滚
  }
}